package sipus.action.master.helper;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.util.GenericAutowireComposer;
import org.zkoss.zul.Button;
import org.zkoss.zul.Label;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Row;
import org.zkoss.zul.Textbox;

import sipus.common.Common;
import sipus.common.CommonPrivilages;
import sipus.common.DesEncrypter;
import sipus.database.dao.DaoFactory;
import sipus.database.dao.TbmuserDao;
import sipus.database.hibernate.HibernateUtil;
import sipus.database.model.Tbmuser;


public class ResetPasswordHelper extends GenericAutowireComposer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6947829244115144706L;

	private Row rowNama;
	private Row rowButton;
	private Label labelNama;
	private Textbox userid;
	private Button reset;
	private Tbmuser tbmuser;

	@Override
	public void doAfterCompose(Component comp) throws Exception {
		// TODO Auto-generated method stub
		super.doAfterCompose(comp);
		if (session.getAttribute("usersTemp") == null
				|| !CommonPrivilages.checkPrevilages(CommonPrivilages.READ)) {
			session.removeAttribute("usersTemp");
			execution.sendRedirect("/logoff");
			return;
		}
		reset.setDisabled(true);

		reset.addEventListener("onClick", new EventListener() {

			@Override
			public void onEvent(Event event) throws Exception {
				// TODO Auto-generated method stub

				if (onReset()) {
					String pesan = "";
					if (tbmuser != null) {
						pesan = tbmuser.getUserId();
					}
					Messagebox.show("Password untuk User ID : "
							+ userid.getValue() + " telah diset menjadi : "
							+ pesan);
					System.out.println("Password untuk User ID : "
							+ userid.getValue() + " telah diset menjadi : "
							+ pesan);

					reset.setDisabled(true);

				}

			}
		});

	}

	public void onCari() throws Exception {
		if (userid.getValue().equals("")) {
			Messagebox.show("Masukkan User ID", "Peringatan", Messagebox.OK,
					Messagebox.EXCLAMATION);
			return;
		}

		Session session = HibernateUtil.currentSession();
		tbmuser = (Tbmuser) session.createCriteria(Tbmuser.class)
				.add(Restrictions.eq("userId", userid.getValue()))
				.uniqueResult();

		rowNama.setVisible(true);
		labelNama.setValue(tbmuser.getUserNama());

		rowButton.setVisible(true);
		reset.setDisabled(false);

	}

	public boolean onReset() throws Exception {
		DesEncrypter desEncrypter = Common.desEncrypter;
		if (tbmuser != null) {
			TbmuserDao tbmuserDao = DaoFactory.getInstance().getTbmuserDao();
			tbmuser.setUserPassword(desEncrypter.encrypt(tbmuser.getUserId()));
			tbmuserDao.update(tbmuser);
		}

		return true;

	}

}
